﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using CarShop.Domain.Entities;

namespace CarShop.Security.Contracts
{

    [Serializable]
    public class CarShopIdentity : IIdentity
    {
        private readonly string _name = "Anonymous";
        private readonly int _id;
        private readonly List<string> _roles;


        public static CarShopIdentity Anonymous
        {
            get { return new CarShopIdentity(); }
        }

        public int Id
        {
            get { return _id; }
        }

        public string Name
        {
            get { return _name; }
        }

        public string AuthenticationType
        {
            get { return "CarShopAuth"; }
        }

        public bool IsAuthenticated
        {
            get { return _id != default(int); }
        }

        public IEnumerable<string> Roles
        {
            get { return _roles; }
        }


        public CarShopIdentity(User user)
        {
            _name = user.Login;
            _id = user.Id;
            _roles = new List<string>(user.Roles.Select(r => r.Name));
        }

        public CarShopIdentity(int userId, string name, IEnumerable<string> roles)
        {
            _id = userId;
            _name = name;
            _roles = new List<string>(roles);
        }

        private CarShopIdentity()
        {
            _roles = new List<string>();
        }


        public string Serialize()
        {
            var binaryFormatter = new BinaryFormatter();
            var memoryStream = new MemoryStream();
            binaryFormatter.Serialize(memoryStream, this);

            return Convert.ToBase64String(memoryStream.ToArray());
        }

        public static CarShopIdentity Deserialize(string data)
        {
            var bytes = Convert.FromBase64String(data);
            var binaryFormatter = new BinaryFormatter();

            return (CarShopIdentity)binaryFormatter.Deserialize(new MemoryStream(bytes));
        }
    }

}
